import { defineStore } from "pinia";
import { baseURL } from "@/api";
import { LoginForm, LoginUser } from "@/api/login/index";
import LoginApi from "@/api/login";
import { clearToken, setToken } from "@/utils/cacheUtils";
import { ChatMessage } from "@/api/chat/message/model";
import FileApi from "@/api/file";

export const useUserStore = defineStore("user", () => {
  /**
   * 当前用户信息
   */
  const userInfo = useStorage<LoginUser>("userInfo", {});

  /**
   * 聊天未读新消息
   */
  const chatMessage = useStorage<ChatMessage[]>("chatMessage", []);

  /**
   * 登录
   * @param loginForm
   */
  const login = async (loginForm: LoginForm) => {
    clearToken();
    clearMessage();
    const { success, message, data } = await LoginApi.login(loginForm);
    if (success) {
      setToken(data.accessToken, data.refreshToken);
      data.user.avatarUrl =
        data.user.avatarUrl == "" ? FileApi.GetDefaultUserAvatar() : baseURL + data.user.avatarUrl;
      Object.assign(userInfo.value, { ...data.user });
    } else {
      ElMessage({
        message: message,
        type: "error",
      });
    }
    return success;
  };

  function clearMessage() {
    chatMessage.value = [];
  }

  return {
    userInfo,
    login,
    isOnline: ref(true),
    chatMessage,
    clearMessage,
  };
});
